# Assigns balancing authorities to nerc regions 
# See HMMY Appendix H
# - BA's except MISO and PJM: Assign to nerc region 
#   (Ignore cases where small # of generators in BA are assigned to multiple nerc)
# - Assign generators from MISO to MRO nerc region
# - Assign generators from PJM to RFC nerc region.
# - Give California its own region 

library(pacman)
p_load(
  here, fst, data.table, readxl, janitor
)

# Reading the unit info table
unit_info_dt = 
  read.fst(
    path = here("Data/electricity-generation/unit-info-dt.fst"),
    as.data.table = TRUE
  )

# Merging them all together
ba_region_dt = rbind(
  ba_region18_dt[
    ba_region18_dt[,.(max_index = .I[N == max(N)]), by = ba_code]$max_index,
    .(
      ba_code, 
      nerc_adj = fcase(
        ba_code == "MISO", "MRO",
        ba_code == "PJM", "RFC",
        ba_code %in% c("BANC","CISO","IID","LDWP","TIDC"), "CAL",
        !is.na(nerc), nerc
      ),
      year = 2018
    )
  ],
  ba_region19_dt[
    ba_region19_dt[,.(max_index = .I[N == max(N)]), by = ba_code]$max_index,
    .(
      ba_code, 
      nerc_adj = fcase(
        ba_code == "MISO", "MRO",
        ba_code == "PJM", "RFC",
        ba_code %in% c("BANC","CISO","IID","LDWP","TIDC"), "CAL",
        !is.na(nerc), nerc
      ),
      year = 2019
    )
  ],
  ba_region20_dt[
    ba_region20_dt[,.(max_index = .I[N == max(N)]), by = ba_code]$max_index,
    .(
      ba_code, 
      nerc_adj = fcase(
        ba_code == "MISO", "MRO",
        ba_code == "PJM", "RFC",
        ba_code %in% c("BANC","CISO","IID","LDWP","TIDC"), "CAL",
        !is.na(nerc), nerc
      ),
      year = 2020
    )
  ]
)

# GRID and GLHB are not in eGRID data
ba_region_dt = 
  rbind(
    ba_region_dt,
    data.table(ba_code = c("GRID","GLHB"), nerc_adj = c("WECC","MRO"), year = 2018),
    data.table(ba_code = c("GRID","GLHB"), nerc_adj = c("WECC","MRO"), year = 2019),
    data.table(ba_code = c("GRID","GLHB"), nerc_adj = c("WECC","MRO"), year = 2020)
  )

# Saving the results 
fwrite(
  ba_region_dt,
  here("Data/electricity-generation/ba-region-xwalk.csv")
)
